NOTE
Remove Duplicates from Sorted List II
LeetCode notes on Remove Duplicates from Sorted List II.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Given the head head of a sorted linked list, delete all nodes whose values are duplicated, leaving only values that appear once. Return the sorted linked list.
2. Approach
Compared with Remove Duplicates from Sorted List, this adds an if/else branch.
3. Implementation
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteDuplicates(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
dummyHead := &ListNode{}
d := dummyHead
current := head
for current != nil {
next := current.Next
current.Next = nil
if next != nil && current.Val == next.Val {
for next != nil && current.Val == next.Val {
next = next.Next
}
} else {
d.Next = current
d = d.Next
}
current = next
}
return dummyHead.Next
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub